// ValidationAspects
// Written by Mike Saunders
// Released under Microsoft Public License (Ms-PL)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using ValidationAspects.Sdk;

namespace ValidationAspects.Configuration
{
	public class MethodValidation : IMethodValidation
	{
		public string Method { get; set; }
		public ValidationApplication Apply { get; set; }
		public List<IValidatorFactory> Validators { get; set; }
		public List<IParameterValidation> Parameters { get; set; }

		public MethodValidation()
		{
			Validators = new List<IValidatorFactory>();
			Parameters = new List<IParameterValidation>();
		}

		public void Register(Type type)
		{
			Enforce.IsNotNull(type, "type");
			Enforce.IsNotNullOrEmpty(Method, "Method");

			MethodInfo methodInfo = type.GetMethods(BindingFlags.Instance | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic).FirstOrDefault(m => m.ToString() == Method);
			if (methodInfo == null)
				throw new ValidationConfigurationException(string.Format("Method [name:{0}] [type:{1}] is unknown.", Method, type));

			// set method declaring instance validators
			if (Apply == ValidationApplication.Replace)
				methodInfo.ReplaceValidation(Validators);
			else
				methodInfo.AddValidation(Validators);

			// set parameter validators
			foreach (IParameterValidation parameter in Parameters)
			{
				parameter.Register(methodInfo);
			}
		}
	}
}